﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Text;
using System.Web.SessionState;

namespace jnagr.Web.areainfo
{
    /// <summary>
    /// GetArea 的摘要说明
    /// </summary>
    public class GetArea : IHttpHandler, IRequiresSessionState
    {
        jnagr.BLL.areainfo bll = new jnagr.BLL.areainfo();
        StringBuilder result = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        public void ProcessRequest(HttpContext context)
        {

            string ac = "";
            if (null != context.Request.Form["action"])
            {//获取前台传来的值  
                ac = context.Request.Form["action"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["action"])
            {
                ac = context.Request.QueryString["action"].ToString().Trim();
            }

            if (ac == "query")
                Query(context);
            else if (ac == "add")
                add(context);
            else if (ac == "modify")
                modify(context);
            else if (ac == "delete")
                delete(context);
            else if (ac == "ddllist")
                ddllist(context);
            else if (ac == "deletemy")
                deletemy(context);
            else if (ac == "addmynode")
                addmy(context);
            else if (ac == "querymy")
                Querymy(context);
            else if (ac == "querypro")
                Querypro(context);//省级地区在我的地区里面找的－－我的地区功能淘汰！
            else if (ac == "querymypro")
                Querymypro(context);//取得一个省的地区信息
            else if (ac == "querymyarea")
                Querymyarea(context);//取我下级地区信息列表
            else if (ac == "querymyareaall")
                Querymyareaall(context);//取我下级所有地区信息树
            else if (ac == "querymyareauser")
                Querymyareauser(context);//取我下级所有地区信息树
            else if (ac == "querymyco")
                Querymyco(context);//取我下级所有地区信息到县树--！~~~~~~~~~~~~~~~
            else if (ac == "queryyb")
                Queryyb(context);
            else if (ac == "queryyb9")//不取县级以下地区
                QueryybNO9(context);
            else if (ac == "queryarea")//根据编码取地区
                QueryareaBybm(context);
        }
        public void QueryareaBybm(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                jnagr.BLL.myarea mybll = new BLL.myarea();
                string bm = "";
                if (!string.IsNullOrEmpty(context.Request.QueryString["bm"]))
                {
                    bm=context.Request.QueryString["bm"].ToString();
                }
                string areas = bll.GetAare(bm);
               
                context.Response.Write(areas);
                context.Response.End();
            }
        }
        public void Querymyco(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                string[] pcc = Web.Admin.myinfo.getPCC(context).Split(',');
                int level = Web.Admin.myinfo.getLevel(context);
                int aid = bll.GetAid(level, pcc);
                string myp = "";
                if (level > 3) myp = "全国";
                else if (level == 3) myp = pcc[0];
                else if (level == 2) myp = pcc[1];
                else if (level == 1) myp = pcc[2];
                DataSet ds = bll.GetList("LEN(abh)<>9");
                result.Remove(0, result.Length);
                string strb = GetTreeJsonByTable(ds.Tables[0], "aid", "aname", "pid", aid);
                strb = "[{\"id\":" + aid + ",\"text\":\"" + myp + "\",\"children\":" + strb + "}]";
                context.Response.Write(strb);//返回给前台页面  
                context.Response.End();
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();
            }
        }

        private string GetTreeJsonByTableNoleaf(DataTable tabel, string idCol, string txtCol, string rela, object pId)
        {
            result.Append(sb.ToString());
            sb.Remove(0, sb.Length);
            if (tabel.Rows.Count > 0)
            {
                sb.Append("[");
                string filer = string.Format("{0}='{1}'", rela, pId);
                DataRow[] rows = tabel.Select(filer);
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"bm\":\"" + row["abh"] + "\"");
                        if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                        {
                            //点击展开
                            sb.Append(",\"children\":");
                            GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
                            result.Append(sb.ToString());
                            sb.Remove(0, sb.Length);
                        }
                        result.Append(sb.ToString());
                        sb.Remove(0, sb.Length); ;
                        sb.Append("},");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("]");
                result.Append(sb.ToString());
                sb.Remove(0, sb.Length);
            }
            return result.ToString();
        }

        public void Querymyareaall(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                string[] pcc = Web.Admin.myinfo.getPCC(context).Split(',');
                int level = Web.Admin.myinfo.getLevel(context);
                int aid = bll.GetAid(level, pcc);
                DataSet ds = bll.GetList("");
                result.Remove(0, result.Length);
                string strb = GetTreeJsonByTable(ds.Tables[0], "aid", "aname", "pid", aid);
                //string strb = GetTreeJsonByTable(ds.Tables[0], "aid", "aname", "2");
                //strb = "{\"id\":-2,\"text\":\"分地区浏览\",\"children\":[{\"id\":" + aid + ",\"text\":\"" + myp + "\",\"children\":" + strb + "}]}";
                string strJson = "[{\"id\":" + aid + ",\"text\":\"全部\",\"children\":" + strb + "}]";
                context.Response.Write(strJson);//返回给前台页面  
                context.Response.End();
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }
        public void deletemy(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                int uid = 0;
                string uidstr = context.Request.QueryString["maid"];
                if (uidstr != "")
                    uid = int.Parse(uidstr);
                jnagr.BLL.myarea mybll = new BLL.myarea();
                if (mybll.Delete(uid))
                {
                    context.Response.Write("T");//返回给前台页面  
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("F");//返回给前台页面  
                    context.Response.End();

                }
            }

        }
        public void Querymy(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                jnagr.BLL.myarea mybll = new BLL.myarea();
                int uid = Web.Admin.myinfo.getID(context);
                DataSet ds = mybll.GetListv(" uid=" + uid);
                string str = GetTreeJsonByTableOne(ds.Tables[0], "maid", "aname", "abh");
                context.Response.Write(str);//返回给前台页面  
                context.Response.End();
            }
        }
        private string GetTreeJsonByTableOne(DataTable tabel, string idCol, string txtCol, string bmCol)
        {
            result.Remove(0, result.Length);
            if (tabel.Rows.Count > 0)
            {
                result.Append("[");

                foreach (DataRow row in tabel.Rows)
                {
                    result.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] +"\",\"state\": \"closed\",\"bm\":\"" + row[bmCol] + "\"},");
                }
                result = result.Remove(result.Length - 1, 1);

                result.Append("]");

            }
            return result.ToString();
        }
        public void Querypro(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                string pro = Web.Admin.myinfo.getPCC(context).Split(',')[0];

                StringBuilder strWhere = new StringBuilder();
                if (pro != "")
                {
                    strWhere.AppendFormat(" province='{0}'  ", pro);
                }
                jnagr.BLL.myarea mybll = new BLL.myarea();
                DataSet ds = mybll.GetListv(strWhere.ToString());
                string str = GetTreeJsonByTableOne(ds.Tables[0], "maid", "aname", "abh");
                context.Response.Write(str);//返回给前台页面  
                context.Response.End();
            }
        }
        public void ddllist(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                DataSet ds = bll.GetList("");
                string strJson = ToJson.DataTable2Json1(ds.Tables[0]);//DataSet数据转化为Json数据  
                context.Response.Write(strJson);//返回给前台页面  
                context.Response.End();
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }
        public void delete(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                int aid = 0;
                string uidstr = context.Request.QueryString["aid"];
                if (uidstr != "")
                    aid = int.Parse(uidstr);
                if (bll.Delete(aid))
                {
                    context.Response.Write("T");//返回给前台页面  
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("F");//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();
            }
        }
        public void modify(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                int mid = 0;
                string uidstr = context.Request.Form["aid"];
                if (uidstr != "")
                    mid = int.Parse(uidstr);
                string mname = context.Request.Form["aname"];
                string bh = context.Request.Form["abh"];
                jnagr.Model.areainfo model = new jnagr.Model.areainfo();

                model.aname = mname;
                model.abh = bh;
                model.aid = mid;
                if (bll.Update(model))
                {
                    context.Response.Write("T");//返回给前台页面  
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("F");//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();
            }
        }
        public void add(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string hname = context.Request.Form["aname"];
            string hbm = context.Request.Form["abh"];
            string province = Web.Admin.myinfo.getPCC(context).Split(',')[0];
            if (province != "")
            {
                int parentid = 0;
                if (context.Request.Form["parentid"] != "")
                    parentid = int.Parse(context.Request.Form["parentid"]);
                jnagr.Model.areainfo model = new jnagr.Model.areainfo();
                model.aname = hname;
                model.pid = parentid;
                model.abh = hbm;
                //model.province = province;
                if (bll.Add(model) > 0)
                {
                    context.Response.Write("T");//返回给前台页面  
                    context.Response.End();

                }
                else
                {
                    context.Response.Write("F");//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();
            }

        }
        public void addmy(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int aid = 0;
            string aids = context.Request.QueryString["aid"];
            if (aids != "") aid = int.Parse(aids);
            if (aid != 0)
            {
                string province = Web.Admin.myinfo.getPCC(context).Split(',')[0];
                int uid = Web.Admin.myinfo.getID(context);
                if (province != "")
                {
                    jnagr.Model.myarea model = new jnagr.Model.myarea();
                    model.aid = aid;
                    model.uid = uid;
                    model.province = province;
                    jnagr.BLL.myarea mybll = new BLL.myarea();
                    if (mybll.Add(model) > 0)
                    {
                        context.Response.Write("T");//返回给前台页面  
                        context.Response.End();

                    }
                    else
                    {
                        context.Response.Write("F");//返回给前台页面  
                        context.Response.End();
                    }
                }
                else
                {
                    context.Response.Write("L");//返回给前台页面  
                    context.Response.End();
                }
            }

        }
        public void QueryybNO9(HttpContext context)//异步 不到县级以下单位
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                if (Web.Admin.myinfo.isLogin(context))
                {
                    int parentId = -1;
                    if (!string.IsNullOrEmpty(context.Request.QueryString["pid"]))
                    {
                        Int32.TryParse(context.Request.QueryString["pid"], out parentId);
                    }
                    if (parentId >= 0)
                    {
                        List<jnagr.Model.areainfo> areas = bll.GetModelList("len(abh)<>9 and pid=" + parentId);
                        string resultStr = "";
                        
                        resultStr += "[";
                        foreach (jnagr.Model.areainfo item in areas)
                        {
                            int i = bll.GetRecordCount("len(abh)<>9 and pid=" + item.aid);

                            resultStr += "{";
                            if (i > 0)
                                resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"bm\": \"{2}\", \"state\": \"closed\"", item.aid.ToString(), item.aname, item.abh);
                            else
                                resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"bm\": \"{2}\"", item.aid.ToString(), item.aname, item.abh);


                            resultStr += "},";
                        }
                        resultStr = resultStr.Substring(0, resultStr.Length - 1);
                        resultStr += "]";
                        context.Response.Write(resultStr);//返回给前台页面  
                        context.Response.End();
                    }
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }
        public void Queryyb(HttpContext context)//异步
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                if (Web.Admin.myinfo.isLogin(context))
                {
                    int parentId = -1;
                    if (!string.IsNullOrEmpty(context.Request.QueryString["pid"]))
                    {
                        Int32.TryParse(context.Request.QueryString["pid"], out parentId);
                    }
                    if (parentId >= 0)
                    {
                        List<jnagr.Model.areainfo> areas = bll.GetModelList("pid=" + parentId);
                        string resultStr = "";
                       
                        resultStr += "[";
                        foreach (jnagr.Model.areainfo item in areas)
                        {
                            int i=bll.GetRecordCount("pid=" + item.aid);
                           
                            resultStr += "{";
                            if (i > 0)
                            resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"bm\": \"{2}\", \"state\": \"closed\"", item.aid.ToString(), item.aname,item.abh);
                            else
                                resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"bm\": \"{2}\"", item.aid.ToString(), item.aname, item.abh);
                            

                            resultStr += "},";
                        }
                        resultStr = resultStr.Substring(0, resultStr.Length - 1);
                        resultStr += "]";
                        context.Response.Write(resultStr);//返回给前台页面  
                        context.Response.End();
                    }
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }
        public void Query(HttpContext context)
        {


            context.Response.ContentType = "text/plain;charset=gb2312";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                if (Web.Admin.myinfo.isLogin(context))
                {
                    //string pro = Web.Admin.myinfo.getPCC(context).Split(',')[0];

                    //StringBuilder strWhere = new StringBuilder();
                    //if (pro != "")
                    //{
                    //    strWhere.AppendFormat(" province='{0}'  ", pro);
                    //}
                    DataSet ds = bll.GetList("");

                    string str = GetTreeJsonByTable(ds.Tables[0], "aid", "aname", "pid", 0);
                    context.Response.Write(str);//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }
        public void Querymypro(HttpContext context)//取得一个省的树
        {


            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                if (Web.Admin.myinfo.isLogin(context))
                {
                    string pro = Web.Admin.myinfo.getPCC(context).Split(',')[0];
                    DataSet ds = bll.GetList("");
                    string str = GetTreeJsonByTablewhere(ds.Tables[0], "aid", "aname", "pid", 0, pro);
                    context.Response.Write(str);//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }
        private string GetTreeJsonByTablewhere(DataTable tabel, string idCol, string txtCol, string rela, object pId, string wherename)
        {
            result.Append(sb.ToString());
            sb.Remove(0, sb.Length);
            if (tabel.Rows.Count > 0)
            {
                sb.Append("[");
                string filer;
                if (pId.ToString() == "0") filer = string.Format("{0}='{1}' and " + txtCol + "='" + wherename + "'", rela, pId);
                else
                    filer = string.Format("{0}='{1}'", rela, pId);
                DataRow[] rows = tabel.Select(filer);
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"bm\":\"" + row["abh"] + "\"");
                        if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                        {
                            //点击展开
                            sb.Append(",\"children\":");
                            GetTreeJsonByTablewhere(tabel, idCol, txtCol, rela, row[idCol], wherename);
                            result.Append(sb.ToString());
                            sb.Remove(0, sb.Length);
                        }
                        result.Append(sb.ToString());
                        sb.Remove(0, sb.Length); ;
                        sb.Append("},");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("]");
                result.Append(sb.ToString());
                sb.Remove(0, sb.Length);
            }
            return result.ToString();
        }
        public void Querymyareauser(HttpContext context)//取得一个地区下的地区的列表 所有用户都可用
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                if (Web.Admin.myinfo.isLogin(context))
                {
                    string[] pcc = Web.Admin.myinfo.getPCC(context).Split(',');
                    int level = Web.Admin.myinfo.getLevel(context);
                    int aid = bll.GetAid(level, pcc);
                    string abh = bll.GetAbh(level, pcc);
                    DataSet ds = bll.GetList("pid=" + aid);
                    string str = GetTreeJsonByTableOne(ds.Tables[0], "aid", "aname", "abh");
                    if (level == -1 || level == 3)
                        str = "[{\"id\":\"-" + 3 + "\",\"text\":\"" + pcc[0] + "\",\"bm\":\"" + abh + "\",\"children\":" + str + "}]";
                    else if (level == 5|| level==4)
                        str = "[{\"id\":\"-" + level + "\",\"text\":\"全国\",\"bm\":\"0\",\"children\":" + str + "}]";
                    else
                        str = "[{\"id\":\"-" + level + "\",\"text\":\""+string.Join("",pcc)+"\",\"bm\":\"" + abh + "\",\"children\":" + str + "}]";
                    context.Response.Write(str);//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }

        public void Querymyarea(HttpContext context)//取得一个地区下的地区的列表只有管理员和县级代理能用
        {
            context.Response.ContentType = "text/plain";
            int uid = Web.Admin.myinfo.getID(context);
            if (uid != 0)
            {
                if (Web.Admin.myinfo.isLogin(context))
                {
                    string[] pcc = Web.Admin.myinfo.getPCC(context).Split(',');
                    int level = Web.Admin.myinfo.getLevel(context);
                    int aid = bll.GetAid(level, pcc);
                    DataSet ds = bll.GetList("pid=" + aid);
                    string str = GetTreeJsonByTableOne(ds.Tables[0], "aid", "aname", "abh");
                    if(level==-1)
                    str = "[{\"id\":\"" + level + "\",\"text\":\""+pcc[0]+"\",\"children\":" + str + "}]";
                    context.Response.Write(str);//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();

            }
        }
        private string GetTreeJsonByTablemyarea(DataTable tabel, string idCol, string txtCol, string rela, object pId, string wherename)
        {
            result.Append(sb.ToString());
            sb.Remove(0, sb.Length);
            if (tabel.Rows.Count > 0)
            {
                sb.Append("[");
                string filer;
                if (pId.ToString() == "0") filer = string.Format("{0}='{1}' and " + txtCol + "='" + wherename + "'", rela, pId);
                else
                    filer = string.Format("{0}='{1}'", rela, pId);
                DataRow[] rows = tabel.Select(filer);
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"bm\":\"" + row["abh"] + "\"");
                        if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                        {
                            //点击展开
                            sb.Append(",\"children\":");
                            GetTreeJsonByTablewhere(tabel, idCol, txtCol, rela, row[idCol], wherename);
                            result.Append(sb.ToString());
                            sb.Remove(0, sb.Length);
                        }
                        result.Append(sb.ToString());
                        sb.Remove(0, sb.Length); ;
                        sb.Append("},");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("]");
                result.Append(sb.ToString());
                sb.Remove(0, sb.Length);
            }
            return result.ToString();
        }
        private string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
        {
            result.Append(sb.ToString());
            sb.Remove(0, sb.Length);
            if (tabel.Rows.Count > 0)
            {
                sb.Append("[");
                string filer = string.Format("{0}='{1}'", rela, pId);
                DataRow[] rows = tabel.Select(filer);
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"bm\":\"" + row["abh"] + "\"");
                        if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                        {
                            //点击展开
                            sb.Append(",\"children\":");
                            GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
                            result.Append(sb.ToString());
                            sb.Remove(0, sb.Length);
                        }
                        result.Append(sb.ToString());
                        sb.Remove(0, sb.Length); ;
                        sb.Append("},");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("]");
                result.Append(sb.ToString());
                sb.Remove(0, sb.Length);
            }
            return result.ToString();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}